#include "MysqlConnectionPool.h"


MySQLConnectionPool::MySQLConnectionPool(const char* host, const char* user, const char* password, const char* db, int port, int poolSize)  
    : host_(host), user_(user), password_(password), db_(db), port_(port), poolSize_(poolSize), availableConnections_(0) {  
    for (int i = 0; i < poolSize; ++i) {  
        MYSQL* conn = createConnection();  
        if (conn) {  
            connections_.push_back(conn);  
            ++availableConnections_;  
        } else {  
            throw std::runtime_error("Failed to create MySQL connection");  
        }  
    }  
}  
  
MySQLConnectionPool::~MySQLConnectionPool() {  
    for (MYSQL* conn : connections_) {  
        mysql_close(conn);  
    }  
}  
  
MYSQL* MySQLConnectionPool::createConnection() {  
    MYSQL* conn = mysql_init(nullptr);  
    if (conn == nullptr) {  
        return nullptr;  
    }  
  
    if (mysql_real_connect(conn, host_, user_, password_, db_, port_, nullptr, 0) == nullptr) {  
        mysql_close(conn);  
        return nullptr;  
    }  
  
    return conn;  
}  
  
MYSQL* MySQLConnectionPool::getConnection() {  
    std::unique_lock<std::mutex> lock(mtx_);  
    cv_.wait(lock, [this] { return availableConnections_ > 0; });  
  
    MYSQL* conn = connections_.back();  
    connections_.pop_back();  
    --availableConnections_;  
  
    lock.unlock();  
    return conn;  
}  
  
void MySQLConnectionPool::releaseConnection(MYSQL* conn) {  
    std::unique_lock<std::mutex> lock(mtx_);  
    connections_.push_back(conn);  
    ++availableConnections_;  
    cv_.notify_one();  
}